package com.fbs.wowo.wx.service;

import com.fbs.wowo.exception.DataOverflowException;
import com.fbs.wowo.exception.ErrorCode;
import com.fbs.wowo.wx.web.TicketController;
import com.fbs.wowo.wx.wxUtil.HttpUtils;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

@Service
public class PreAuthCodeService {

    @Resource
    private AccessTokenService accessTokenService;

    public String getPreAuthCode() {
        String url =
                "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token="
                        + accessTokenService.getWxAccessToken();
        HashMap<String, String> map = new HashMap<>();
        map.put("component_appid", TicketController.appId);
        JSONObject jsonParam = JSONObject.fromObject(map);
        String returnData = HttpUtils.post(url, jsonParam.toString());
        System.out.println("getPreAuthCode:\n"+returnData+"\n\n");
        JSONObject json = JSONObject.fromObject(returnData);
        if (json.containsKey("pre_auth_code")) {
            if (json.get("pre_auth_code") != null && !json.get("pre_auth_code").equals("")) {
                return json.get("pre_auth_code").toString();
            }
        }
        throw new DataOverflowException(ErrorCode.ERR_WX_PREAUTHCODE_NULL);
    }
}
